package com.project.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.StudentBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class StudentServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setContentType("application/json;charset=utf-8");
       List<StudentBean> list = new ArrayList<StudentBean>();
       list.add(new StudentBean("tom",18, LocalDate.parse("1998-08-05")));
       list.add(new StudentBean("rose",20, LocalDate.parse("1995-10-05")));
       list.add(new StudentBean("jack",19, LocalDate.parse("1991-06-05")));

       ObjectMapper om = new ObjectMapper();
       //注册新日期类型
       om.registerModule(new JavaTimeModule());
//       //将对象转化为json格式字符串
//       String str = om.writeValueAsString(list);
//
//       resp.getWriter().println(str);
        //将对象转化为json字符串输出到客户端
        om.writeValue(resp.getWriter(),list);
    }
}
